from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot
from pymonad import Either, Result, Error

from RBK.Model.Functions import createModel,\
                                addRow,\
                                isCore,\
                                removeRow,\
                                runQuery


class DataType(QObject):
    errored = pyqtSignal(str)

    def __init__(self, db):
        super().__init__()
        self.db = db
        self.models = self.db.models

    @pyqtSlot(str)
    def addDataType(self, text):
        dataTable = 'Data {0}'.format(text)
        structTable = 'Struct {0}'.format(text)

        if(text=='DataTypes'):
            result = runQuery(self.db.db, 'CREATE TABLE DataTypes (DataType TEXT PRIMARY KEY)') >> \
                     createModel(self.db, 'DataTypes')
        else:
            # if it is a core rulebook, set up the DataType structure.
            # Otherwise, just create the Data table
            if(isCore(self.db.db)):
                result = runQuery(self.db.db, 'CREATE TABLE "{0}" ("Field Name" TEXT PRIMARY KEY, Type TEXT, Constraints TEXT, "User Editable?" TEXT)'.format(structTable)) >> \
                         runQuery(self.db.db, 'INSERT INTO "{0}" ("Field Name", Type, Constraints, "User Editable?") VALUES ("Name", "Text", "maxLength(50)", "False")'.format(structTable)) >> \
                         runQuery(self.db.db, 'INSERT INTO "{0}" ("Field Name", Type, Constraints, "User Editable?") VALUES ("Rulebook PDF Destination", "Text", "maxLength(50)", "False")'.format(structTable)) >> \
                         runQuery(self.db.db, 'INSERT INTO "{0}" ("Field Name", Type, Constraints, "User Editable?") VALUES ("Character Sheet Field", "Text", "maxLength(50)", "False")'.format(structTable)) >> \
                         createModel(self.db, structTable)
            result = runQuery(self.db.db, 'CREATE TABLE "{0}" (Name TEXT PRIMARY KEY, "Rulebook PDF Destination" TEXT, "Character Sheet Field" TEXT)'.format(dataTable))

        if result == Result(True):
            createModel(self.db, dataTable)
            if not (text=='DataTypes'):
                addRow(self.db, self.models['DataTypes'], text)
        else:
            message = result.getValue()
            self.errored.emit(message)


    @pyqtSlot(str)
    def removeDataType(self, dt):
        dataTable = 'Data {0}'.format(dt)
        structTable = 'Struct {0}'.format(dt)

        removeRow(self.db, self.models['DataTypes'], dt)
        self.models['DataTypes'].select()

        self.models.pop(dataTable)
        self.models.pop(structTable)
        result = runQuery(self.db.db, 'DROP TABLE "{0}"'.format(dataTable)) >> \
                 runQuery(self.db.db, 'DROP TABLE "{0}"'.format(structTable))

        if result != Result(True):
            message = result.getValue()
            self.errored.emit(message)
